<?php
/**
 * Author: Administrator
 * Date: 2022/7/23 23:36
 */

namespace DesignPatterns\Behavioral\Iterator;


class BookListReverseIterator implements \Iterator
{

    protected BookList $bookList;
    protected int $currentIdx;

    public function __construct(BookList $bookList)
    {
        $this->bookList = $bookList;
        $this->currentIdx = count($bookList) - 1;
    }

    /**
     * @inheritDoc
     */
    public function current(): mixed
    {
        return $this->bookList->getBook($this->currentIdx);
    }

    /**
     * @inheritDoc
     */
    public function next(): void
    {
        $this->currentIdx--;
    }

    /**
     * @inheritDoc
     */
    public function key(): int
    {
        return $this->currentIdx;
    }

    /**
     * @inheritDoc
     */
    public function valid(): bool
    {
        return $this->currentIdx >= 0;
    }

    /**
     * @inheritDoc
     */
    public function rewind(): void
    {
        $this->currentIdx = count($this->bookList) - 1;
    }
}